using Godot;

[Tool]
public partial class DeathZone : Area2D
{
    [ExportGroup("Settings")]
    [Export]
    public Vector2 ZoneSize
    {
        get => _zoneSize;
        set { _zoneSize = value; UpdateZone(); }
    }
    private Vector2 _zoneSize = new Vector2(100, 100);

    [Export]
    public bool IsActive
    {
        get => _isActive;
        set { _isActive = value; UpdateZone(); }
    }
    private bool _isActive = true;

    // --- 视觉参数更新 ---
    [ExportGroup("Visuals (Shader)")]
    [Export] public Color BaseColor = new Color(1.2f, 0.0f, 0.95f, 0.9f); // 鲜艳的红
    [Export] public float GlowIntensity = 1.5f; // 强度要高，配合HDR
    [Export] public float FlowSpeed = 2.0f;     // 流动速度
    [Export] public float StripeDensity = 10.0f; // 条纹密度
    [Export(PropertyHint.Range, "0,1")] public float EdgeSoftness = 0.0f; // 边缘柔化

    [ExportGroup("Internal Refs")]
    [Export] public CollisionShape2D Collider;
    [Export] public ColorRect VisualRect;

    public override void _Ready()
    {
        if (!Engine.IsEditorHint())
        {
            BodyEntered += OnBodyEntered;
            AreaEntered += OnAreaEntered;
        }
        UpdateZone();
    }

    private void UpdateZone()
    {
        // 1. 设置碰撞体
        if (Collider != null)
        {
            if (Collider.Shape == null || !Collider.Shape.IsLocalToScene())
                Collider.Shape = new RectangleShape2D();
            if (Collider.Shape is RectangleShape2D rect)
                rect.Size = _zoneSize;
        }

        // 2. 设置视觉参数
        if (VisualRect != null)
        {
            VisualRect.Size = _zoneSize;
            VisualRect.Position = -_zoneSize / 2.0f;
            VisualRect.Visible = _isActive;

            if (VisualRect.Material is ShaderMaterial mat)
            {
                mat.SetShaderParameter("base_color", BaseColor);
                mat.SetShaderParameter("intensity", GlowIntensity);
                mat.SetShaderParameter("speed", FlowSpeed);
                mat.SetShaderParameter("density", StripeDensity);
                mat.SetShaderParameter("softness", EdgeSoftness);

                // ---  传递实际大小给 Shader ---
                mat.SetShaderParameter("size", _zoneSize);
            }
        }

        Monitoring = _isActive;
    }

    private void OnBodyEntered(Node2D body)
    {
        if (!IsActive) return;

        if (body is PlayerController player)
        {
            player.Die();


            return;
        }
    }
    private void OnAreaEntered(Area2D area)
    {

        if (!IsActive) return;
        if (area is AnchorBullet bullet)
        {

            GD.Print("死亡区域吞噬了子弹喵！");
            bullet.QueueFree();
        }
    }

    // private void ReloadLevel()
    // {
    //     SceneTransition.Instance.ReloadCurrentScene();
    // }
    public void SetActive(bool active)
    {
        IsActive = active;
    }
}